package ynu.edu.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ynu.edu.entities.Address;
import ynu.edu.entities.BaseResponse;
import ynu.edu.service.AddressService;

import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    private static final Logger logger = LoggerFactory.getLogger(AddressController.class);

    @Autowired
    private AddressService addressService;

    /**
     * 根据用户ID查询送货地址列表
     */
    @GetMapping("/list/{userId}")
    public BaseResponse<List<Address>> listAddressByUserId(@PathVariable("userId") String userId) {
        logger.info("接收到查询用户地址列表请求，userId: {}", userId);
        try {
            // 验证userId
            if (userId == null || userId.trim().isEmpty()) {
                logger.warn("查询用户地址列表失败：userId为空或无效");
                return new BaseResponse<>(400, "用户ID不能为空", null);
            }
            
            logger.info("开始调用地址服务查询地址列表，userId: {}", userId);
            BaseResponse<List<Address>> response = addressService.listAddressByUserId(userId);
            logger.info("查询用户地址列表成功，userId: {}, 返回码: {}, 地址数量: {}", 
                userId, response.getCode(), response.getData() != null ? response.getData().size() : 0);
            return response;
        } catch (Exception e) {
            logger.error("查询用户地址列表异常，userId: {}, 异常类型: {}, 错误信息: {}", 
                userId, e.getClass().getName(), e.getMessage(), e);
            return new BaseResponse<>(500, "地址服务暂时不可用，请稍后再试", null);
        }
    }

    /**
     * 根据地址ID查询送货地址
     */
    @GetMapping("/{daId}/{userId}")
    public BaseResponse<Address> getAddressById(@PathVariable("daId") Integer daId, @PathVariable("userId") String userId) {
        logger.info("接收到查询地址详情请求，daId: {}, userId: {}", daId, userId);
        try {
            Address address = addressService.getAddressById(daId, userId);
            if (address != null) {
                logger.info("查询地址详情成功，daId: {}, userId: {}", daId, userId);
                return new BaseResponse<>(200, "获取地址成功", address);
            } else {
                logger.warn("地址不存在，daId: {}, userId: {}", daId, userId);
                return new BaseResponse<>(404, "地址不存在", null);
            }
        } catch (Exception e) {
            logger.error("查询地址详情异常，daId: {}, userId: {}, 异常类型: {}, 错误信息: {}", 
                daId, userId, e.getClass().getName(), e.getMessage(), e);
            return new BaseResponse<>(500, "地址服务暂时不可用，请稍后再试", null);
        }
    }

    /**
     * 新增送货地址
     */
    @PostMapping("/save")
    public BaseResponse<Address> saveAddress(@RequestBody Address address) {
        logger.info("接收到保存地址请求，address: {}", address);
        try {
            // 验证必要字段
            if (address == null || address.getUserId() == null || address.getUserId().trim().isEmpty()) {
                logger.warn("保存地址失败：地址对象为空或用户ID为空");
                return new BaseResponse<>(400, "地址信息或用户ID不能为空", null);
            }
            
            BaseResponse<Address> response = addressService.saveAddress(address);
            logger.info("保存地址成功，address: {}", response.getData());
            return response;
        } catch (Exception e) {
            logger.error("保存地址异常，address: {}, 异常类型: {}, 错误信息: {}", 
                address, e.getClass().getName(), e.getMessage(), e);
            return new BaseResponse<>(500, "地址服务暂时不可用，请稍后再试", null);
        }
    }

    /**
     * 更新送货地址
     */
    @PutMapping("/update")
    public BaseResponse<Address> updateAddress(@RequestBody Address address) {
        logger.info("接收到更新地址请求，address: {}", address);
        try {
            // 验证必要字段
            if (address == null || address.getDaId() == null || address.getUserId() == null) {
                logger.warn("更新地址失败：地址对象为空或地址ID/用户ID为空");
                return new BaseResponse<>(400, "地址信息、地址ID或用户ID不能为空", null);
            }
            
            BaseResponse<Address> response = addressService.updateAddress(address);
            logger.info("更新地址成功，address: {}", response.getData());
            return response;
        } catch (Exception e) {
            logger.error("更新地址异常，address: {}, 异常类型: {}, 错误信息: {}", 
                address, e.getClass().getName(), e.getMessage(), e);
            return new BaseResponse<>(500, "地址服务暂时不可用，请稍后再试", null);
        }
    }

    /**
     * 删除送货地址
     */
    @DeleteMapping("/delete/{daId}/{userId}")
    public BaseResponse<Void> deleteAddress(@PathVariable("daId") Integer daId, @PathVariable("userId") String userId) {
        logger.info("接收到删除地址请求，daId: {}, userId: {}", daId, userId);
        try {
            // 验证参数
            if (daId == null || userId == null || userId.trim().isEmpty()) {
                logger.warn("删除地址失败：地址ID或用户ID为空");
                return new BaseResponse<>(400, "地址ID或用户ID不能为空", null);
            }
            
            BaseResponse<Void> response = addressService.deleteAddress(daId, userId);
            logger.info("删除地址成功，daId: {}, userId: {}", daId, userId);
            return response;
        } catch (Exception e) {
            logger.error("删除地址异常，daId: {}, userId: {}, 异常类型: {}, 错误信息: {}", 
                daId, userId, e.getClass().getName(), e.getMessage(), e);
            return new BaseResponse<>(500, "地址服务暂时不可用，请稍后再试", null);
        }
    }
    
    /**
     * 设置默认地址
     */
    @PutMapping("/default/{userId}/{daId}")
    public BaseResponse<Address> setDefaultAddress(@PathVariable("userId") String userId, @PathVariable("daId") Integer daId) {
        logger.info("接收到设置默认地址请求，userId: {}, daId: {}", userId, daId);
        try {
            // 验证参数
            if (userId == null || userId.trim().isEmpty() || daId == null) {
                logger.warn("设置默认地址失败：用户ID或地址ID为空");
                return new BaseResponse<>(400, "用户ID或地址ID不能为空", null);
            }
            
            // 获取要设置为默认的地址
            Address address = addressService.getAddressById(daId, userId);
            if (address == null) {
                logger.warn("设置默认地址失败：地址不存在，userId: {}, daId: {}", userId, daId);
                return new BaseResponse<>(404, "地址不存在", null);
            }
            
            // 设置为默认地址
            address.setIsDefault(1);
            BaseResponse<Address> response = addressService.updateAddress(address);
            logger.info("设置默认地址成功，userId: {}, daId: {}", userId, daId);
            return response;
        } catch (Exception e) {
            logger.error("设置默认地址异常，userId: {}, daId: {}, 异常类型: {}, 错误信息: {}", 
                userId, daId, e.getClass().getName(), e.getMessage(), e);
            return new BaseResponse<>(500, "地址服务暂时不可用，请稍后再试", null);
        }
    }
} 